package com.itheima.aspect;

import com.itheima.mapper.LoginMapper;
import com.itheima.pojo.LoginInfo;
import com.itheima.pojo.LoginLog;
import com.itheima.pojo.login.Dto;
import com.itheima.utils.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;

@Slf4j
@Aspect
public class RecordTimeAspect {

    @Autowired
    private LoginMapper loginMapper;
    @Around("execution(* com.itheima.service.*.*(..))")
    //往数据库中增加日志记录
    public Object loginLog(ProceedingJoinPoint pjp) throws Throwable {
        //记录方法执行开始时间
        long begin = System.currentTimeMillis();

        //获取方法参数名
        Object[] args = pjp.getArgs();
        Dto arg = (Dto) args[0];
        String username = arg.getUsername();
        String password = arg.getPassword();

        LoginLog loginLog = new LoginLog();
        loginLog.setUsername(username);
        loginLog.setPassword(password);

        //操作时间
        loginLog.setOperateTime(LocalDateTime.now());

        boolean isSuccess = false;
        //执行目标方法
        Object result = null;
        String token =null;
        try {
            result = pjp.proceed();
            if (result instanceof LoginInfo){
                LoginInfo loginInfo = (LoginInfo) result;
                token = loginInfo.getToken();
            }
            isSuccess = true;
            loginLog.setIsSuccess(isSuccess);

        } catch (Throwable e) {
            loginLog.setIsSuccess(false);
        }finally {
            long end = System.currentTimeMillis();

            //方法耗时
            log.info("方法耗时 {} ms" ,(end-begin));
            loginLog.setCostTime(end-begin);
            loginLog.setJwt(token);
        }


        //记录方法执行结束时间

        return result;
    }


}
